/*
 * Copyright 2017-2020 吴学文 and java110 team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.java110.mall.acct.smo.impl;


import com.java110.core.annotation.Java110Transactional;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.integral.IntegralDto;
import com.java110.dto.integral.PreStoreUserIntegralDto;
import com.java110.dto.integral.IntegralDetailDto;
import com.java110.dto.storeOrder.StoreOrderLedgerAcctDto;
import com.java110.intf.acct.IIntegralDetailV1InnerServiceSMO;
import com.java110.mall.acct.dao.IIntegralV1ServiceDao;
import com.java110.intf.acct.IIntegralV1InnerServiceSMO;
import com.java110.po.integral.IntegralPo;
import com.java110.po.integral.IntegralDetailPo;
import com.java110.utils.lock.DistributedLock;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.core.base.smo.BaseServiceSMO;
import com.java110.dto.PageDto;
import com.java110.utils.util.ListUtil;
import com.java110.utils.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * 类表述： 服务之前调用的接口实现类，不对外提供接口能力 只用于接口建调用
 * add by 吴学文 at 2024-05-23 22:54:47 mail: 928255095@qq.com
 * open source address: https://gitee.com/wuxw7/MicroCommunity
 * 官网：http://www.homecommunity.cn
 * 温馨提示：如果您对此文件进行修改 请不要删除原有作者及注释信息，请补充您的 修改的原因以及联系邮箱如下
 * // modify by 张三 at 2021-09-12 第10行在某种场景下存在某种bug 需要修复，注释10至20行 加入 20行至30行
 */
@RestController
public class IntegralV1InnerServiceSMOImpl extends BaseServiceSMO implements IIntegralV1InnerServiceSMO {

    @Autowired
    private IIntegralV1ServiceDao integralV1ServiceDaoImpl;

    @Autowired
    private IIntegralDetailV1InnerServiceSMO integralDetailV1InnerServiceSMOImpl;


    @Override
    public int saveIntegral(@RequestBody IntegralPo integralPo) {
        int saveFlag = integralV1ServiceDaoImpl.saveIntegralInfo(BeanConvertUtil.beanCovertMap(integralPo));
        return saveFlag;
    }

    @Override
    public int updateIntegral(@RequestBody IntegralPo integralPo) {
        int saveFlag = integralV1ServiceDaoImpl.updateIntegralInfo(BeanConvertUtil.beanCovertMap(integralPo));
        return saveFlag;
    }

    @Override
    public int deleteIntegral(@RequestBody IntegralPo integralPo) {
        integralPo.setStatusCd("1");
        int saveFlag = integralV1ServiceDaoImpl.updateIntegralInfo(BeanConvertUtil.beanCovertMap(integralPo));
        return saveFlag;
    }

    @Override
    public List<IntegralDto> queryIntegrals(@RequestBody IntegralDto integralDto) {

        //校验是否传了 分页信息

        int page = integralDto.getPage();

        if (page != PageDto.DEFAULT_PAGE) {
            integralDto.setPage((page - 1) * integralDto.getRow());
        }

        List<IntegralDto> integrals = BeanConvertUtil.covertBeanList(integralV1ServiceDaoImpl.getIntegralInfo(BeanConvertUtil.beanCovertMap(integralDto)), IntegralDto.class);

        return integrals;
    }


    @Override
    public int queryIntegralsCount(@RequestBody IntegralDto integralDto) {
        return integralV1ServiceDaoImpl.queryIntegralsCount(BeanConvertUtil.beanCovertMap(integralDto));
    }

    @Override
    @Java110Transactional
    public int preStoreUserIntegral(@RequestBody PreStoreUserIntegralDto preStoreUserIntegralDto) {


        if (StringUtil.isEmpty(preStoreUserIntegralDto.getIntegralId())) {
            throw new IllegalArgumentException("账户ID为空");
        }
        //开始枷锁
        String requestId = DistributedLock.getLockUUID();
        String key = preStoreUserIntegralDto.getIntegralId();
        IntegralDto integralDto = null;
        List<IntegralDto> integralDtos = null;
        int flag;
        try {
            DistributedLock.waitGetDistributedLock(key, requestId);
            integralDto = new IntegralDto();
            integralDto.setIntegralId(preStoreUserIntegralDto.getIntegralId());
            integralDtos = queryIntegrals(integralDto);
            if (ListUtil.isNull(integralDtos)) {
                throw new IllegalArgumentException("小区金币账户不存在");
            }
            //在账户增加
            double amount = Double.parseDouble(integralDtos.get(0).getAmount());
            BigDecimal amountBig = new BigDecimal(amount);
            amount = amountBig.add(new BigDecimal(preStoreUserIntegralDto.getAmount())).doubleValue();
            IntegralPo integralPo = new IntegralPo();
            integralPo.setIntegralId(integralDtos.get(0).getIntegralId());
            integralPo.setAmount(amount + "");
            flag = updateIntegral(integralPo);
            if (flag < 1) {
                throw new IllegalArgumentException("更新账户失败");
            }
        } finally {
            DistributedLock.releaseDistributedLock(requestId, key);
        }

        IntegralDetailPo integralDetailPo = new IntegralDetailPo();
        integralDetailPo.setDetailType(IntegralDetailDto.DETAIL_TYPE_IN);
        integralDetailPo.setAmount(preStoreUserIntegralDto.getAmount()+"");
        integralDetailPo.setOrderId(preStoreUserIntegralDto.getOrderId());
        integralDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId("11"));
        integralDetailPo.setIntegralId(preStoreUserIntegralDto.getIntegralId());
        integralDetailPo.setRemark(preStoreUserIntegralDto.getRemark());
        integralDetailPo.setRelIntegralId("-1");
        integralDetailPo.setObjId(integralDtos.get(0).getObjId());
        integralDetailPo.setObjType(integralDtos.get(0).getObjType());
        integralDetailPo.setLink(integralDtos.get(0).getLink());

        integralDetailV1InnerServiceSMOImpl.saveIntegralDetail(integralDetailPo);


        return 1;
    }


    @Override
    @Java110Transactional
    public int preStoreIntegral(@RequestBody StoreOrderLedgerAcctDto storeOrderLedgerAcctDto) {


        if (StringUtil.isEmpty(storeOrderLedgerAcctDto.getPayAcctId())) {
            throw new IllegalArgumentException("账户ID为空");
        }
        //开始枷锁
        String requestId = DistributedLock.getLockUUID();
        String key = storeOrderLedgerAcctDto.getPayAcctId();
        IntegralDto integralDto = null;
        List<IntegralDto> integralDtos = null;
        int flag;
        try {
            DistributedLock.waitGetDistributedLock(key, requestId);
            integralDto = new IntegralDto();
            integralDto.setIntegralId(storeOrderLedgerAcctDto.getPayAcctId());
            integralDtos = queryIntegrals(integralDto);
            if (ListUtil.isNull(integralDtos)) {
                throw new IllegalArgumentException("小区金币账户不存在");
            }
            //在账户增加
            double amount = Double.parseDouble(integralDtos.get(0).getAmount());
            BigDecimal amountBig = new BigDecimal(amount);
            amount = amountBig.add(new BigDecimal(Double.parseDouble(storeOrderLedgerAcctDto.getAmount()))).doubleValue();
            IntegralPo integralPo = new IntegralPo();
            integralPo.setIntegralId(integralDtos.get(0).getIntegralId());
            integralPo.setAmount(amount + "");
            flag = updateIntegral(integralPo);
            if (flag < 1) {
                throw new IllegalArgumentException("更新账户失败");
            }
        } finally {
            DistributedLock.releaseDistributedLock(requestId, key);
        }

        IntegralDetailPo integralDetailPo = new IntegralDetailPo();
        integralDetailPo.setDetailType(IntegralDetailDto.DETAIL_TYPE_IN);
        integralDetailPo.setAmount(storeOrderLedgerAcctDto.getAmount());
        integralDetailPo.setOrderId(storeOrderLedgerAcctDto.getOrderId());
        integralDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId("11"));
        integralDetailPo.setIntegralId(storeOrderLedgerAcctDto.getPayAcctId());
        integralDetailPo.setRemark("购买商品赠送的积分");
        integralDetailPo.setObjId(integralDtos.get(0).getObjId());

        integralDetailV1InnerServiceSMOImpl.saveIntegralDetail(integralDetailPo);


        return 1;
    }

    @Override
    @Java110Transactional
    public int withholdIntegral(@RequestBody IntegralDetailPo integralDetailPo) {


        if (StringUtil.isEmpty(integralDetailPo.getIntegralId())) {
            throw new IllegalArgumentException("积分ID为空");
        }
        //开始枷锁
        String requestId = DistributedLock.getLockUUID();
        String key = integralDetailPo.getIntegralId();
        IntegralDto integralDto = null;
        List<IntegralDto> integralDtos = null;
        int flag;
        try {
            DistributedLock.waitGetDistributedLock(key, requestId);
            integralDto = new IntegralDto();
            integralDto.setIntegralId(integralDetailPo.getIntegralId());
            integralDtos = queryIntegrals(integralDto);
            if (ListUtil.isNull(integralDtos)) {
                throw new IllegalArgumentException("积分账户不存在");
            }
            //在账户增加
            double amount = Double.parseDouble(integralDtos.get(0).getAmount());
            BigDecimal amountBig = new BigDecimal(amount);
            amount = amountBig.subtract(new BigDecimal(Double.parseDouble(integralDetailPo.getAmount()))).doubleValue();
            IntegralPo integralPo = new IntegralPo();
            integralPo.setIntegralId(integralDtos.get(0).getIntegralId());
            integralPo.setAmount(amount + "");
            flag = updateIntegral(integralPo);
            if (flag < 1) {
                throw new IllegalArgumentException("更新账户失败");
            }
        } finally {
            DistributedLock.releaseDistributedLock(requestId, key);
        }

        integralDetailPo.setDetailType(IntegralDetailDto.DETAIL_TYPE_OUT);
        if (StringUtil.isEmpty(integralDetailPo.getOrderId())) {
            integralDetailPo.setOrderId("-1");
        }
        if (StringUtil.isEmpty(integralDetailPo.getDetailId())) {
            integralDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId("11"));
        }

        integralDetailPo.setObjId(integralDtos.get(0).getObjId());
        integralDetailPo.setObjType(integralDtos.get(0).getObjType());
        if (StringUtil.isEmpty(integralDetailPo.getRemark())) {
            integralDetailPo.setRemark("购买商品赠送的抵扣金");
        }

        if (StringUtil.isEmpty(integralDetailPo.getRelIntegralId())) {
            integralDetailPo.setRelIntegralId("-1");
        }


        integralDetailV1InnerServiceSMOImpl.saveIntegralDetail(integralDetailPo);

        return 0;
    }

}
